/**
 * @file LoginPage.jsx
 * @description 登录页面组件。
 */
import React, { useState } from 'react';
import { Link, useNavigate, useLocation } from 'react-router-dom';
import { useDispatch } from 'react-redux';
import { loginSuccess } from '../store/authSlice';
import toast from 'react-hot-toast';

const LoginPage = () => {
  const [email, setEmail] = useState(''); // 注意：这里我们还是用 email 变量名，但它也可以是用户名 'admin'
  const [password, setPassword] = useState('');
  const [validated, setValidated] = useState(false);
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const location = useLocation();

  const handleSubmit = (e) => {
    e.preventDefault();
    const form = e.currentTarget;
    if (form.checkValidity() === false) {
      e.stopPropagation();
      toast.error('请输入有效的凭据。'); // 更通用的错误提示
      setValidated(true);
      return;
    }
    setValidated(true);

    let loginSuccessful = false;
    let loggedInUser = null;

    // 首先检查是否是 admin 用户
    if (email === 'admin' && password === 'admin') {
      loggedInUser = { id: 1, name: '管理员', email: 'admin@system.local' }; // 给admin一个固定的email
      loginSuccessful = true;
    } else {
      // 如果不是 admin，则检查 localStorage 中的注册用户
      const registeredUsers = JSON.parse(localStorage.getItem('registeredUsers')) || [];
      const foundUser = registeredUsers.find(user => user.email === email && user.password === password);

      if (foundUser) {
        // 从存储的完整用户对象中提取用于登录状态的部分信息
        loggedInUser = { id: foundUser.id, name: foundUser.name, email: foundUser.email };
        loginSuccessful = true;
      }
    }

    if (loginSuccessful && loggedInUser) {
      dispatch(loginSuccess(loggedInUser));
      toast.success('登录成功！');
      const from = location.state?.from?.pathname || "/";
      navigate(from, { replace: true });
    } else {
      toast.error('邮箱或密码错误！');
    }
  };

  return (
    <div className="container my-3 py-3">
      <h1 className="text-center">登录</h1>
      <hr />
      <div className="row my-4 h-100 justify-content-center">
        <div className="col-md-6 col-lg-5 col-sm-8">
          <div className="card p-4 shadow">
            <form className={`needs-validation ${validated ? 'was-validated' : ''}`} noValidate onSubmit={handleSubmit}>
              <div className="mb-3">
                <label htmlFor="loginEmail">邮箱地址 / 用户名</label>
                <input
                  type="text"
                  className="form-control"
                  id="loginEmail"
                  placeholder="请输入邮箱或 'admin'"
                  value={email}
                  onChange={(e) => setEmail(e.target.value)}
                  required
                />
                <div className="invalid-feedback">
                  请输入您的邮箱或用户名。
                </div>
              </div>
              <div className="mb-3">
                <label htmlFor="loginPassword">密码</label>
                <input
                  type="password"
                  className="form-control"
                  id="loginPassword"
                  placeholder="请输入密码或 'admin'"
                  value={password}
                  onChange={(e) => setPassword(e.target.value)}
                  required
                />
                <div className="invalid-feedback">
                  请输入您的密码。
                </div>
              </div>
              <div className="my-3">
                <p>还没有账户? <Link to="/register" className="text-decoration-underline text-info">注册</Link></p>
              </div>
              <div className="text-center">
                <button className="btn btn-dark w-100" type="submit">
                  登录
                </button>
              </div>
            </form>
          </div>
        </div>
      </div>
    </div>
  );
};

export default LoginPage;